import json
import re

from django.db.models import constants
from django.shortcuts import render
# Create your views here.
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area, Address
from django.core.cache import cache

from utlis.views import LoginRequiredJSONMixin


# 省份
class AreaView(View):

    def get(self, request):
        prv_list = []
        # 查询省份缓存
        a = request.GET.get('province')
        if a is None:
            # 查询省份
            province = Area.objects.filter(parent=None)  # 此为查询结果集

            # 组织数据
            # 将对象转换为字典

            for i in province:
                prv_list.append({
                    'id': i.id,
                    'name': i.name
                })
                # 存储省份缓存
            cache.set('province', prv_list, 24 * 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': prv_list})


# 市,区
class CityView(View):

     def get(self, request,id):
        # 获取缓存
        my_list = []
        city = request.GET.get('city_%s' % id)
        if city is None:
            parent_id = Area.objects.get(id=id)
            # subs:related_name='subs' 关联模型的名字
            info = parent_id.subs.all()  # 获取省份下的城市信息

            for i in info:
                my_list.append({
                    'id': i.id,
                    'name': i.name
                })
            # 缓存
            cache.set('city_%s' % id, my_list, 24 * 3600)

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'sub_data': {'subs': my_list}
        })



"""
增 post
删 delete
改 put
查 get
"""

# 收货地址
class AddView(LoginRequiredJSONMixin, View):

    def post(self, request):

        count = request.user.addresses.count()
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过最大地址上限'})

        #  接收参数
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数有误'})

        address = Address.objects.create(user=request.user, title=receiver,
                                         receiver=receiver,
                                         province_id=province_id,
                                         city_id=city_id,
                                         district_id=district_id,
                                         place=place,
                                         mobile=mobile,
                                         tel=tel,
                                         email=email)
        # 将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'data.address': address_dict})


class AddressView(LoginRequiredJSONMixin, View):

    """展示收货地址"""
    def get(self, request):
        user = request.user
        # 获取所有地址信息
        # filter 查询结果集
        address_info = Address.objects.filter(user=user, is_deleted=False)
        # print(type(address_info))
        my_list = []
        for address in address_info:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            # 如果只有一个地址则设置这个地址为默认地址
            if address_info.count() == 1:
                request.user.default_address = address
                request.user.save()
            # 判断地址是否为默认是则放在第一位展示
            default_address = request.user.default_address
            if default_address.id == address.id:
                my_list.insert(0, address_dict)
            else:
                my_list.append(address_dict)

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'addresses': my_list,
            'default_address_id': request.user.default_address_id
        })


class DeleteView(LoginRequiredJSONMixin, View):
    """删除地址"""
    def delete(self, request, address_id):
        # 查询到要删除的数据
        address = Address.objects.get(id=address_id)
        address.is_deleted = 1
        # if request.user.default_address==True:
        #     request.user.default_address=False
        # request.user.save()
        address.save()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    """修改地址"""
    def put(self, request, address_id):

        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数有误'})

        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # print(type(a))
        except:
            return JsonResponse({'code': 0, 'errmsg': '地址更新失败'})

        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class DefaultView(LoginRequiredJSONMixin, View):
    """设置默认地址"""
    def put(self, request, address_id):
        address = Address.objects.get(id=address_id)
        request.user.default_address = address
        request.user.save()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class TittleView(View):
    """设置地址标题"""

    def put(self,request,address_id):

        data = json.loads(request.body.decode())
        title=data.get('title')
        address = Address.objects.get(id=address_id)
        address.title =title
        address.save()

        return JsonResponse({'code':0,'errmsg':'ok'})